#! /usr/bin/perl

#--------------------------------------------------
# Verify the integrity of Emdeon returned data for
# insurance2.
#
# If the returned data is good, script
#    exit(0)
# Otherwise
#    exit(1)
#
#--------------------------------------------------
use strict;
use ReportUtils;

our %sent_records  = ();
our %return_records= ();
our $email_msg;

our $recipients = 'christophe@medlytix.com;yi.yan@medlytix.com;arvind@medlytix.com';


sub usage() {
	print STDERR "$0 mmddyy_hhmmss_000cid datafile";
}

#-----------------------------------------------
# send_alert(data_file, error_msg)
#
#  Send out Emdeon file's error to admin
#-----------------------------------------------
sub send_alert($$) 
{
    my $datfile = shift;
    my $err = shift;

    $datfile =~ s#^.*/##;

    my @emails = split( /[,;]/, $recipients);
    return if @emails == 0;
    my $receiver = shift @emails ;
    my $cc = (@emails > 0)?  join ',', @emails : "";

    my $msg = MIME::Lite->new(
        From    => 'support@medlytix.com',
        To      => $receiver,
        Bcc     => $cc,
        Subject => 'Emdeon data error: ' . $datfile,
        Data    => "$err"
        );
    return if ! $msg;

    $msg->send('smtp', 'mailhost', Timeout => 600);
}


#--------------------------------------------------
# get_sent_records(db_hdl, cust_id, our_run_date)
#
#   Read records in insurance1_sent_detail_t for
# particular customer's specific run date.
#--------------------------------------------------
sub get_sent_records ($$$) 
{
	my $dbh     = shift;
	my $cust_id = shift;
	my $ordate  = shift;

	my $sql = "select carrier_code, emdeon_out from insurance1_sent_detail_t " .
		      " where cust_id = $cust_id and our_run_date = \'$ordate\' ";

	my $sth = $dbh->prepare($sql);
	return if ! $sth;
	$sth->execute();
	if( $sth->rows == 0 ) {
		$sth->finish();
		return;
	}

	while( my @result = $sth->fetchrow_array() ) {
		my $key = $result[0];
		$key =~ s/\s//g;
		$sent_records{$key} = $result[1]; 
	}
	$sth->finish();
}


my $batch_recv_date  = $ARGV[0];
my $data_file = $ARGV[1];


if(! -f "$data_file" ) {
	print STDERR "-- not readable: $data_file\n"; 
	exit(1); 
}

my ($ordate, $cust_id)  = $batch_recv_date =~ /^(\d{6}_\d{6})_(\d{6})/;
$cust_id =~ s/^0+//;

if ( $ordate =~ /^\d{6}_\d{6}/ ) {
	my($m,$d,$y,$hh,$mm,$ss) = $ordate 
		=~ /^(\d\d)(\d\d)(\d\d)_(\d\d)(\d\d)(\d\d)/;
	$y += 2000;
	my $ts = "$m/$d/$y $hh:$mm:$ss";
	$ordate = $ts;
}

my $g_dbschema = "payorintel";
my $g_dbbasename="$ENV{USER}" || "mlprod" ;
my $g_dbname=$g_dbbasename . "_db";
my $g_dbuser=$g_dbschema . "_" . $g_dbbasename . "_u";

my $ru = ReportUtils->new();
my $g_dbh = $ru->connect_db($g_dbname, $g_dbuser);
if (defined $g_dbh) {
	get_sent_records ($g_dbh, $cust_id, $ordate); 
	$g_dbh->disconnect();
}
else {
	print STDERR "-- trouble to access database\n";
	exit(1);
}

#foreach my $k (sort keys %sent_records ) { print "$k, $sent_records{$k} \n"; } print "-----\n";

open(DHD, $data_file);
while( my $record = <DHD> ) {
	my $carrier;

	next if $record =~ /^M2;/i;
 
	if( $record =~ /^Remediated;(\d{5});/i) {	
		$carrier = $1;
		$return_records{$carrier} += 1;
		if($record =~ /(RH0923|RH0925)/ ) {
			$return_records{$carrier . '_ERR'} += 1;
		}	
	}
	elsif($record =~ /^(00024|MEDICARE)\;/) {
		$return_records{'00024'} += 1;
		if($record =~ /(RH0923|RH0925)/ ) {
			$return_records{'00024_ERR'} += 1;
		}	
	}
}
close DHD;

#foreach my $k ( sort keys %return_records ) { print "$k, $return_records{$k} \n"; }

my $match =0;
#-----------------------------------------------------
# Require either 00196 or 00029 matches, because these
# two carrier codes co-exists for a data file. 
#-----------------------------------------------------
if( exists $sent_records{'00196'} and 
    exists $return_records{'00196'} and 
     $sent_records{'00196'} == $return_records{'00196'} )
{
	$match = 1;
}
elsif( exists $sent_records{'00029'} and 
       exists $return_records{'00029'} and 
	$sent_records{'00029'} == $return_records{'00029'} )
{
	$match = 1;
}

if( ! $match ) {
	$email_msg .= "\n00196: sent=" . $sent_records{'00196'} 
		. " return=" . $return_records{'00196'} ;
	$email_msg .= "\n00029: sent=" . $sent_records{'00029'} 
		. " return=" . $return_records{'00029'} ;
}

#-----------------------------------------------------
# Require all other carrier's count matches 
#-----------------------------------------------------
foreach my $k ( keys %sent_records ) {
	next if $k =~ /^(00196|00029)$/;
	if(! exists $return_records{$k} or
	   $sent_records{$k} != $return_records{$k} ) {
		$match = 0;
		$email_msg .= "\n$k: sent=" . $sent_records{$k} 
			. " return=" . $return_records{$k} ;
	}
}



#-------------------------------------------------------
# Require all carrier code's error count less than 
# total records number.
#-------------------------------------------------------
foreach my $k ( keys %sent_records ) {
	if( $sent_records{$k} <= $return_records{$k . "_ERR"} ) {
		$match = 0;
		$email_msg .= "\n$k: sent=" . $sent_records{$k} 
			. " return err# =" .  $return_records{$k . "_ERR"} ;
	}
}

if(! $match) {
	send_alert($data_file, $email_msg);
	exit 1;
}

exit 0;

